<?php

namespace dk\widget;
use dk\core\Version;

class Css extends Base {
    protected static $instance;

    /**
     * @param \weixin\core\View $plug
     */
    function bindHandle($plug) {
        $plug->regPlug('css', array($this, 'printFiles'));
        $plug->regPlug('cssCode', array($this, 'addCode'));
    }

    /**
     * @return Base
     */
    public static function getInstance() {
        if (!isset(static::$instance)) {
            if($isDev = Version::isDev()){
                self::$instance = new static();
            }else{
                self::$instance = new CssCache();
            }

            self::$instance->setDev($isDev);
        }
        return static::$instance;
    }

    protected $dev = true;

    /**
     * @param boolean $dev
     */
    public function setDev($dev) {
        $this->dev = $dev;
    }

    /**
     * @param $files
     * @return string
     */
    function render(){
        return $this->printFiles($this->request);
    }

    function addCode($code, $index = null, $tag = true){
        if($tag){
            $code = "<style>{$code}</style>";
        }
        if(!Head::isSend()){
            /** @var Head $head */
            $head = Head::getInstance();
            $head->addHtml($code, $index);
            return '';
        }
        return $code;
    }

    function addToHead($files){
        if(!Head::isSend()){
            /** @var Head $head */
            $head = Head::getInstance();
            $head->addCssFile($files);
            return true;
        }
        return false;
    }

    function printFiles($files, $chkHead = true){
        if($chkHead && $this->addToHead($files)){
            return '';
        }

        $html = [];
        $files = array_unique($files);
        foreach ($files as $file) {
            if($this->dev && !strpos($file, '?')){
                $file .= '?r=' . rand();
            }
            $html[] =  '<link rel="stylesheet" type="text/css" href="'
                .  Ui::getInstance()->render(['src' => $file])
                . '" />';
        }
        return implode("\r\n", $html);
    }
}